package io.renren.modules.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.R;
import io.renren.config.UploadFileConfig;
import io.renren.modules.shop.entity.GoodsPic;
import io.renren.modules.shop.mapper.GoodsPicMapper;
import io.renren.modules.shop.service.GoodsPicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class GoodsPicServiceImpl extends ServiceImpl<GoodsPicMapper, GoodsPic> implements GoodsPicService {

    @Autowired
    private UploadFileConfig fileConfig;

    @Override
    public int updateBatch(List<GoodsPic> list) {
        return baseMapper.updateBatch(list);
    }

    @Override
    public int batchInsert(List<GoodsPic> list) {
        return baseMapper.batchInsert(list);
    }

    @Override
    public int updateBatchSelective(List<GoodsPic> list) {
        return baseMapper.updateBatchSelective(list);
    }

    @Override
    public R uploadImg(MultipartFile[] files, HttpServletRequest request) {
        List<String> images = new ArrayList<>();
        for (MultipartFile file : files) {
            //获取绝对路径
            String realPath = fileConfig.getFilePath();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
//            String format=sdf.format(new Date());
            File folder = new File(realPath);
            // 如果文件夹不存在，则创建文件夹
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            Set<String> allowSuffix = new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif"));
            // 获得初始文件名
            String oldName = file.getOriginalFilename();
            //文件后缀
            String suffix = null;
            if (oldName != null) {
                suffix = oldName.substring(oldName.lastIndexOf(".") + 1 );
            }
            if (suffix == null || !allowSuffix.contains(suffix.toLowerCase())) {
                return R.error("文件格式错误！图片支持格式仅为jpg、jpeg、png、gif");
            }
            //文件新名字
            String newName =new Date().getTime() + "." + suffix;

            File targetFile = new File(folder, newName);

            if (!targetFile.exists()) {
                targetFile.mkdirs();
            } else {
                    targetFile.delete();
                }
                try {
                    file.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/uploadFile/" + newName;
                images.add(filePath);
            }
            return R.ok().put("list", images);
    }
}


